var express = require('express');
var router = express.Router();
const fs = require("fs");
const path = require("path");
var xlsx = require('node-xlsx').default;
const puppeteer = require('puppeteer');
const axios = require('axios');
var URL = require('url');
router.get('/login', async (req, res) => {
    let pat = "path"

    let status = await fs.existsSync(pat)
    if (!status) {
        await fs.mkdirSync(pat);
    }



    const browser = await puppeteer.launch({
        //  slowMo: 100,    //放慢速度
        ignoreHTTPSErrors: true,
        defaultViewport: {
            width: 1920,
            height: 1000
        },
        headless: false,
        userDataDir: 'test-profile-dir',
        executablePath: "chrome-win\\chrome.exe",

    });

    const page = await browser.newPage();
    await page.goto("https://www.tianyancha.com", {
        timeout: 0
    });


    fs.exists('path\\token.txt', function (exists) {

        if (exists) {


            // console.log(11122, urlPath);
        } else {
            fs.writeFileSync('path\\token.txt', '', {
                'flag': 'w'
            })
        }
    });


    page.on('response', async response => {
        if (response.url().indexOf('/services/v3/user/cdloginV2') >= 0) {
            let data
            let json = await response.request().postData()
            if (json) {
                data = JSON.parse(json)
            }
            if (data) {

                axios({
                    method: 'post',
                    url: 'https://napi.tianyancha.com/services/v3/user/cdloginV2.json',
                    data: data,
                    headers: {
                        'version': "TYC-Web",

                    }
                }).then((rbc) => {
                    console.log("成功", rbc.data.data.token);

                    fs.writeFileSync('path\\token.txt', rbc.data.data.token.toString(), {
                        'flag': 'w'
                    })

                    res.send({
                        code: 200,
                        msg: "登录成功"
                    })


                }).catch(err => {

                    browser.close();
                })


            }
            // await browser.close();
        }



        // var p = URL.parse(response.url(),true); 

        // if( p.pathname === '/services/v3/user/cdloginV2.json'){
        //     console.log("url",await response.text());
        // }

        // await response.json()

    })


    let cookies = await page.cookies();
    let data = cookies.filter(item => {
        return item.name == 'auth_token'
    })
 
    if (data.length > 0) {

        fs.exists('path\\token.txt', function (exists) {
            if (exists) {
                fs.writeFileSync('path\\token.txt', data[0].value.toString(), {
                    'flag': 'w'
                })

            } else {
                fs.writeFileSync('path\\token.txt', data[0].value, {
                    'flag': 'w'
                })
            }
        });
    }



})

router.post('/', async (req, res) => {
    let { name, pageNum, pageSize } = req.body
    let pat = "path"
    let status = await fs.existsSync(pat)
    if (!status) {
        await fs.mkdirSync(pat);
    }
    // var urlPath = fs.readFileSync('path\\p.txt', 'utf8');
    // console.log("路径是", urlPath);
    // if (urlPath) {
    // let browser;


    // browser = await puppeteer.launch({
    //     //  slowMo: 100,    //放慢速度
    //     ignoreHTTPSErrors: true,
    //     defaultViewport: {
    //         width: 1920,
    //         height: 1000
    //     },
    //     headless: true,
    //     userDataDir: 'test-profile-dir',
    //     // executablePath: urlPath,
    //     // executablePath: puppeteer.executablePath(),
    //     executablePath: "chrome-win\\chrome.exe",
    //     // executablePath: "C:\Program Files/Google/Chrome/Application/chrome.exe",
    //     // ignoreDefaultArgs: ['--enable-automation'],
    //     // ignoreDefaultArgs: ['--enable-automation','--no-sandbox', '--disable-setuid-sandbox'],

    // });

    // } catch (error) {
    //     res.send({
    //         code: 401,
    //         msg: "请正确名称"
    //     });
    // }
    // const page = await browser.newPage();
    // await page.goto("https://www.tianyancha.com", {
    //     timeout: 0
    // });

    // let cookies = await page.cookies();
    // let data = cookies.filter(item => {
    //     return item.name == 'auth_token'
    // })
    // console.log("token", data);

    fs.existsSync('path\\token.txt', function (exists) {

        if (exists) {

        } else {
            fs.writeFileSync('path\\token.txt', 'aaa', {
                'flag': 'w'
            })

        }
    });


    try {
        var token = fs.readFileSync('path\\token.txt', 'utf8');

        console.log("456", token);

        if (token.length == 0) {
            return res.send({
                code: 401,
                msg: "请先登录"
            });

        } else {
            console.log("进来了", token);
            let existsStatus = false
            fs.exists('path\\tianyan.txt', function (exists) {
                existsStatus = exists

                if (exists) {

                    // console.log(11122, urlPath);
                } else {
                    fs.writeFileSync('path\\tianyan.txt', '1', {
                        'flag': 'w'
                    })
                }
            });


            axios({
                method: 'post',
                url: 'https://capi.tianyancha.com/cloud-tempest/web/searchCompanyV3',
                data: {
                    "key": name,
                    "pageNum": pageNum,
                    "pageSize": pageSize,
                    "referer": "search",
                    "sortType": "1",
                    "word": name
                },
                headers: {
                    'x-auth-token': token,
                    'version': "TYC-Web",

                }
            }).then(async (response) => {
                // console.log("成功", response.data.data);


                if (JSON.stringify(response.data.data) != "{}") {


                    let arr = response.data.data.companyList.map((v, index) => {
                        var regExp = new RegExp("\<em\>|\</em\>", "g");
                        v.name = v.name ? v.name.replace(regExp, "") : v.name


                        return {
                            name: v.name,
                            phone: v.phoneList.toString(),
                            firstPositionValue: v.firstPositionValue
                        }
                    })

                    // let zuizong = [];
                    // let title = ["公司名称", "手机号", "法人姓名"]
                    // zuizong.push(title)
                    // arr.forEach(v => {
                    //     let arrInner = []
                    //     arrInner.push(v.name, v.phone, v.firstPositionValue)
                    //     zuizong.push(arrInner)
                    // })
                    // // console.log(555, zuizong);
                    // try {

                    //     const sheetOptions = { '!cols': [{ wch: 30 }, { wch: 20 }, { wch: 10 }] };
                    //     let buffer = xlsx.build([{
                    //         name: 'sheet1',
                    //         data: zuizong
                    //     }], { sheetOptions });
                    //     let pat = 'public'
                    //     if (!fs.existsSync(pat)) {
                    //         fs.mkdirSync(pat);
                    //     }

                    //     if (existsStatus) {
                    //         let urlPath = fs.readFileSync('path\\tianyan.txt', 'utf8');
                    //         let num = parseInt(urlPath.trim()) + 1
                    //         fs.writeFileSync('path\\tianyan.txt', num.toString(), {
                    //             'flag': 'w'
                    //         })
                    //         let urlPathA = fs.readFileSync('path\\tianyan.txt', 'utf8');
                    //         fs.writeFileSync(pat + `\\天眼查${urlPathA.toString()}.xlsx`, buffer, {
                    //             'flag': 'w'
                    //         });
                    //     } else {
                    //         fs.writeFileSync(pat + '\\天眼查1.xlsx', buffer, {
                    //             'flag': 'w'
                    //         });
                    //     }

                    res.send({
                        code: 200,
                        data: {
                            data: arr,
                            // total: response.data.data.companyTotalPage * 100,
                            total: response.data.data.companyTotal,
                            companyTotalPage: response.data.data.companyTotalPage
                        },
                        msg: "成功"
                    });


                    // } catch (err) {
                    //     res.send({
                    //         code: 401,
                    //         msg: "生成表格失败"
                    //     });

                    // }





                } else {
                    res.send({
                        code: 401,
                        msg: "未查询到数据"
                    });


                }

            }).catch(function (error) {
                console.log("未查询到数据", error);
                res.send({
                    code: 401,
                    msg: "未查询到数据"
                });

            });







        }
    } catch (err) {
        res.send({
            code: 401,
            msg: "请先登录"
        });
    }

})
router.post('/daochu', async (req, res) => {
    let { name, pageNum, pageSize } = req.body
    let pat = "path"
    let status = await fs.existsSync(pat)
    if (!status) {
        await fs.mkdirSync(pat);
    }

    fs.exists('path\\token.txt', function (exists) {
        if (exists) {

            // console.log(11122, urlPath);
        } else {
            fs.writeFileSync('path\\token.txt', ' ', {
                'flag': 'w'
            })
        }
    });
    var token = fs.readFileSync('path\\token.txt', 'utf8');

    if (token.length == 0) {
        return res.send({
            code: 401,
            msg: "请先登录"
        });

    } else {
        console.log("进来了", token);
        let existsStatus = false
        fs.exists('path\\tianyan.txt', function (exists) {
            existsStatus = exists

            if (exists) {

                // console.log(11122, urlPath);
            } else {
                fs.writeFileSync('path\\tianyan.txt', '1', {
                    'flag': 'w'
                })
            }
        });


        axios({
            method: 'post',
            url: 'https://capi.tianyancha.com/cloud-tempest/web/searchCompanyV3',
            data: {
                "key": name,
                "pageNum": pageNum,
                "pageSize": pageSize,
                "referer": "search",
                "sortType": "1",
                "word": name
            },
            headers: {
                'x-auth-token': token,
                'version': "TYC-Web",

            }
        }).then(async (response) => {
            // console.log("成功", response.data.data);


            if (JSON.stringify(response.data.data) != "{}") {


                let arr = response.data.data.companyList.map((v, index) => {
                    var regExp = new RegExp("\<em\>|\</em\>", "g");
                    v.name = v.name ? v.name.replace(regExp, "") : v.name


                    return {
                        name: v.name,
                        phone: v.phoneList.toString(),
                        firstPositionValue: v.firstPositionValue
                    }
                })

                let zuizong = [];
                let title = ["公司名称", "手机号", "法人姓名"]
                zuizong.push(title)
                arr.forEach(v => {
                    let arrInner = []
                    arrInner.push(v.name, v.phone, v.firstPositionValue)
                    zuizong.push(arrInner)
                })
                // // console.log(555, zuizong);
                try {

                    const sheetOptions = { '!cols': [{ wch: 30 }, { wch: 20 }, { wch: 10 }] };
                    let buffer = xlsx.build([{
                        name: 'sheet1',
                        data: zuizong
                    }], { sheetOptions });
                    let pat = 'public'
                    if (!fs.existsSync(pat)) {
                        fs.mkdirSync(pat);
                    }

                    if (existsStatus) {
                        let urlPath = fs.readFileSync('path\\tianyan.txt', 'utf8');
                        let num = parseInt(urlPath.trim()) + 1
                        fs.writeFileSync('path\\tianyan.txt', num.toString(), {
                            'flag': 'w'
                        })
                        let urlPathA = fs.readFileSync('path\\tianyan.txt', 'utf8');
                        fs.writeFileSync(pat + `\\天眼查${urlPathA.toString()}.xlsx`, buffer, {
                            'flag': 'w'
                        });
                    } else {
                        fs.writeFileSync(pat + '\\天眼查1.xlsx', buffer, {
                            'flag': 'w'
                        });
                    }

                    res.send({
                        code: 200,

                        msg: "导出成功"
                    });


                } catch (err) {
                    res.send({
                        code: 401,
                        msg: "生成表格失败"
                    });

                }





            } else {
                res.send({
                    code: 401,
                    msg: "未查询到数据"
                });


            }

        }).catch(function (error) {
            console.log("未查询到数据", error);
            res.send({
                code: 401,
                msg: "未查询到数据"
            });

        });







    }


})
module.exports = router;